package cz.uvn.orthopedy.server.jdo;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import cz.uvn.orthopedy.client.entity.Patient;

public final class PatientJdo {
	
	private PatientJdo() {
	}

	public static void editPatient(Patient patient) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Patient.class);
			query.setFilter("id == idParam");
			query.declareParameters("Long idParam");
			query.setUnique(true);
			Patient result = (Patient) query.execute(patient.getId());
			if (result != null) {
				result.setName(patient.getName());
				result.setSurname(patient.getSurname());
				result.setRodneCislo(patient.getRodneCislo());
				result.setInsuranceID(patient.getInsuranceID());
				result.setAddress(patient.getAddress());
				result.setPhoneNumber(patient.getPhoneNumber());
				result.setEmail(patient.getEmail());
				result.setWorkAbsence(patient.isWorkAbsence());
				result.setNadstandard(patient.isNadstandard());
			}
		} finally {
			pm.close();
		}
	}

	public static Long createPatient(Patient patient) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Patient result = pm.makePersistent(patient);
			return result.getId();
		} finally {
			pm.close();
		}
	}
	
	public static void deletePatient(Patient patient) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Patient.class);
			query.setFilter("id == idParam");
			query.declareParameters("Long idParam");
			@SuppressWarnings("unchecked")
			List<Patient> result = (List<Patient>) query.execute(patient.getId());
			assert result.size() == 1;
			pm.deletePersistent(result.get(0));
		} finally {
			pm.close();
		}
	}

	public static Patient[] getPatients() {
		Patient[] patients = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.setDetachAllOnCommit(true);
		try {
			Query q = pm.newQuery(Patient.class);
			q.setOrdering("surname");
			@SuppressWarnings("unchecked")
			List<Patient> result = (List<Patient>) q.execute();
			patients = new Patient[result.size()];
			for (int i = 0; i < result.size(); i++) {
				Patient pat = result.get(i);
				patients[i] = new Patient(pat.getId(), pat.getName(), pat.getSurname(),
						pat.getRodneCislo(), pat.getInsuranceID(), pat.getAddress(),
						pat.getPhoneNumber(), pat.getEmail(), pat.isWorkAbsence(),
						pat.isNadstandard());
			}
		} finally {
			pm.close();
		}
		return patients;
	}

}
